<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Storage;
use Encore\Admin\Facades\Admin;

use App\Models\Photo;
use App\Models\Tag;
use App\Models\Category;

class PhotoController extends Controller
{
    use HasResourceActions;
    public $openstatus = [
        '公开且代表作',
        '公开',
        '私有仅授权可见',
    ];
    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('Index')
            ->description('description')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed   $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed   $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Create')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Photo);

        $grid->id('ID')->sortable();
        $grid->title('标题');
        $grid->image('相册')->display(function () {
            return isset($this->image[0])?$this->image[0]:"";
        })->image('','200','50');
        $grid->column('count','数量')->display(function () {
            return count($this->image);
        });
        $grid->tags('标签')->display(function ($tags){
            return explode(',', $tags);
        })->label();
        $grid->desc('描述');

        $grid->created_at('创建时间');
        $grid->updated_at('修改时间');

        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->column(1/2, function ($filter) {
                $filter->like('title', '标题');
                $filter->like('tags', '标签');
            });
            
            $filter->column(1/2, function ($filter) {
                $filter->between('created_at', '创建时间')->datetime();
            });
        });

        $grid->model()->where('uid', Admin::user()->id);

        $grid->disableExport();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Photo::findOrFail($id));

        $show->id('ID');
        $show->title('标题');
        $show->category_id('分类')->as(function($category_id){
            return Category::find($category_id)->name;
        });

        // $show->image('照片')->image();
        $show->image('照片')->unescape()->as(function ($image) {
            $width = 200; $height = 200;
            $html = array_map(function ($path) {
                $disk = config('admin.upload.disk');
                if (config("filesystems.disks.{$disk}")) {
                    $src = Storage::disk($disk)->url($path);
                } else {
                    return '';
                }
                return "<a href='$src' target='_blank'><img src='$src' style='max-width:200px;max-height:200px' class='img' /></a>";

            }, $image);
            $html = implode(' ', $html);
            return $html;
        });
        $openstatus = $this->openstatus;
        $show->openstate('公开状态')->as(function($openstate)use($openstatus){
            return $openstatus[$openstate];
        })->label();
        $show->tags('关键词')->as(function($tags){
            return explode(',', $tags);
        })->label();
        $show->desc('描述');
        $show->created_at('创建时间');
        $show->updated_at('修改时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Photo);

        $form->display('id', 'ID');
        $form->display('uid', 'UID')->default(Admin::user()->id);
        $form->text('title', '标题')->rules('required'); 
        $form->multipleImage('image', '照片')->removable()->rules(['required']);
        // 分类
        $category = Category::where('type', '1')
               ->get()
               ->pluck('name','id')
               ->all();
        $form->select('category_id', '分类')->options($category)->rules('required');
        $form->select('openstate', '公开状态')->options($this->openstatus)->rules('required');
        $form->text('desc', '描述')->rules(['required']);
        $form->text('tags', '关键词')->rules('required')->attribute(['data-role'=>'tagsinput']);
        // hotwords
        $hotwords = Category::where('type', '2')
            ->pluck('name')
            ->take(10)
            ->all();
        $html = array_map(function ($name) {
            return "<div style='margin: 5px 5px 0px 0px;float:left;'><a href='javascript:void(0)' class='label label-success'>{$name}</a></div>";
        }, $hotwords);
        $html = implode('', $html);
        $form->html($html,'HotWords');
        // 选择预定热词
        // $form->tags('标签')->options($category);

        $form->display('created_at', '创建时间');
        $form->display('updated_at', '修改时间');
        $form->saving(function (Form $form) {
            // 如果不是编辑状态，则添加字段uid
            if (!$id = $form->model()->id) {
                $form->uid = Admin::user()->id;
            }
        });


        Admin::script($this->script());

        return $form;
    }
    protected function script()
    {

        return <<<EOT
$("form").keypress(function(e) {
  if (e.which == 13) {
    add_option();
    return false;
  }
});
// 初始化 tagsinput
$('input[data-role="tagsinput"]').tagsinput({
        itemValue: 'id',
        itemText: 'text',
    });
init();
// 点击hotwords为关键词选项
$(".label-success").on('click', function(e) {

    var new_tag = $(this).html();
    var tag={
        id:new_tag,
        text:new_tag
    };
    $("#tags").tagsinput('add', tag);

    $(this).parent('div').remove();
});
// 关键词增加选项
function add_option(){
    var new_tag = $(".bootstrap-tagsinput>input").val();
    var tag={
        id:new_tag,
        text:new_tag
    };
    $("#tags").tagsinput('add', tag);

    $(".bootstrap-tagsinput>input").val('');
}
//    设定标签原始值
function init(){
    var str = $("#tags").val();
    old_tags = str.split(",");
    if(old_tags[0]){
        for(i=0;i<old_tags.length ;i++){
            $("#tags").tagsinput('add', {id:old_tags[i],text:old_tags[i]})
        }
    }
}
EOT;
    }
}
